package com.zh.common.base

import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.trello.rxlifecycle2.components.support.RxFragment
import com.zh.common.immersion.ImmersionOwner
import com.zh.common.immersion.ImmersionProxy
import com.zh.common.ktx.viewBinding
import com.zh.common.utils.JumpActivity
import com.zh.common.view.dialog.LoadingDialog
import java.lang.reflect.ParameterizedType

/**
 * ......................我佛慈悲....................
 * ......................_oo0oo_.....................
 * .....................o8888888o....................
 * .....................88" . "88....................
 * .....................(| -_- |)....................
 * .....................0\  =  /0....................
 * ...................___/`---'\___..................
 * ..................' \\|     |// '.................
 * ................./ \\|||  :  |||// \..............
 * .............../ _||||| -卍-|||||- \..............
 * ..............|   | \\\  -  /// |   |.............
 * ..............| \_|  ''\---/''  |_/ |.............
 * ..............\  .-\__  '-'  ___/-. /.............
 * ............___'. .'  /--.--\  `. .'___...........
 * .........."" '<  `.___\_<|>_/___.' >' ""..........
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.......
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.......
 * ....=====`-.____`.___ \_____/___.-`___.-'=====....
 * ......................`=---='.....................
 * ..................佛祖开光 ,永无BUG................
 * @auth xiaohua
 * @time 2020/10/7 - 15:21
 * @desc Fragment基类，MVVM架构
 */
abstract class BaseFragment<VB : ViewBinding> : RxFragment(), JumpActivity,
    ImmersionOwner {

    val viewBinding : VB by lazy { viewBinding<VB>() }
    private var rootView: View? = null
    private lateinit var mContext: Context
    private var loadingDialog: LoadingDialog? = null

    //ImmersionBar代理类
    private val mImmersionProxy: ImmersionProxy get() = ImmersionProxy(this)

    override fun initImmersionBar() {
        initImmersionBars()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mImmersionProxy.onCreate()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        ARouter.getInstance().inject(this)
        if (null == rootView) { //如果缓存中有rootView则直接使用
            rootView = viewBinding.root
        } else {
            rootView!!.parent?.let { it2 -> (it2 as ViewGroup).removeView(rootView) }
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //在OnCreate方法中调用下面方法，然后再使用线程，就能在uncaughtException方法中捕获到异常
        initView(savedInstanceState)
        mImmersionProxy.onActivityCreated()
    }

    open val showEmptyView: Boolean = true//是否需要空布局
    open val smartRefresh: SmartRefreshLayout? = null
    abstract fun initView(savedInstanceState: Bundle?)

    override fun onResume() {
        super.onResume()
        mImmersionProxy.onResume()
    }

    override fun onPause() {
        super.onPause()
        mImmersionProxy.onPause()
        //页面消失的时候，软键盘自动关闭
        activity?.let {
            if (KeyboardUtils.isSoftInputVisible(it)) {
                KeyboardUtils.hideSoftInput(it)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //为rootView做缓存，在viewpager中使用fragment时可以提升切换流畅度
        rootView?.let {
            it.parent?.let { it2 -> (it2 as ViewGroup).removeView(it) }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mImmersionProxy.onDestroy()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        mImmersionProxy.isUserVisibleHint = isVisibleToUser
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        mImmersionProxy.onHiddenChanged(hidden)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        mImmersionProxy.onConfigurationChanged(newConfig)
    }

    /**
     * 懒加载，在view初始化完成之前执行
     * On lazy after view.
     */
    override fun onLazyBeforeView() {}

    /**
     * 懒加载，在view初始化完成之后执行
     * On lazy before view.
     */
    override fun onLazyAfterView() {}

    /**
     * Fragment用户可见时候调用
     * On visible.
     */
    override fun onVisible() {}

    /**
     * Fragment用户不可见时候调用
     * On invisible.
     */
    override fun onInvisible() {}

    /**
     * 是否可以实现沉浸式，当为true的时候才可以执行initImmersionBar方法
     * Immersion bar enabled boolean.
     *
     * @return the boolean
     */
    override fun immersionBarEnabled(): Boolean = true

    private fun getLoadingDialog() {
        loadingDialog ?: also { loadingDialog = activity?.let { it1 -> LoadingDialog(it1) } }
    }

    /**
     * 显示加载dialog
     */
    fun showLoading() {
        try {
            getLoadingDialog();loadingDialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 结束dialog
     */
    fun dismissLoading() {
        try {
            loadingDialog?.let { if (it.isShowing) it.dismiss() }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //结束刷新
    private fun finishSmartRefresh() {
        smartRefresh?.let { if (it.isRefreshing) it.finishRefresh(); if (it.isLoading) it.finishLoadMore() }
    }
}